// 用户相关接口
package api

import (
	"gin-admin-api/constant"
	"gin-admin-api/core"
	"gin-admin-api/global"
	"gin-admin-api/model"
	"gin-admin-api/result"
	"gin-admin-api/utils"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

// CreateSysAdmin 新增用户
// @Summary 新增用户
// @Tags 用户相关接口
// @Produce json
// @Description 新增用户
// @Param data body model.AddSysAdminDto true "data"
// @Success 200 {object} result.Result
// @router /api/sysAdmin/add [post]
func CreateSysAdmin(c *gin.Context) {
	// 绑定参数并校验必填
	var dto model.AddSysAdminDto
	_ = c.BindJSON(&dto)
	err := validator.New().Struct(dto)
	if err != nil {
		result.Failed(c, int(result.ApiCode.MisssParameter), result.ApiCode.GetMessage(result.ApiCode.MisssParameter))
		return
	}
	// 用户名称不能重复
	sysAdminByUsername := GetSysAdminByName(dto.Username)
	if sysAdminByUsername.ID > 0 {
		result.Failed(c, int(result.ApiCode.UsernameAlreadyExists), result.ApiCode.GetMessage(result.ApiCode.UsernameAlreadyExists))
		return
	}
	// 新增用户
	sysAdmin := model.SysAdmin{
		Username:   dto.Username,
		Nickname:   dto.Nickname,
		Password:   utils.EncryptionMd5(dto.Password),
		Phone:      dto.Phone,
		Email:      dto.Email,
		Sex:        dto.Sex,
		Note:       dto.Note,
		Status:     dto.Status,
		CreateTime: utils.Htime{Time: time.Now()},
	}
	core.Db.Create(&sysAdmin)
	// 新增用户角色关系
	sysAdminExist := GetSysAdminByName(dto.Username)
	var sysAdminRole model.SysAdminRole
	sysAdminRole.AdminId = sysAdminExist.ID
	sysAdminRole.RoleId = dto.RoleId
	core.Db.Create(&sysAdminRole)

	result.Success(c, true)
}

func GetSysAdminByName(username string) (sysAdmin model.SysAdmin) {
	core.Db.Where("username = ?", username).First(&sysAdmin)
	return sysAdmin
}

// GetSysMenu 根据id查询用户
// @Summary 根据id查询用户
// @Tags 用户相关接口
// @Produce json
// @Description 根据id查询用户
// @Param id query int true "用户id"
// @Success 200 {object} result.Result
// @router /api/sysAdmin/info [get]
func GetSysAdmin(c *gin.Context) {
	Id, _ := strconv.Atoi(c.Query("id"))
	var sysAdminInfo model.SysAdminInfo
	core.Db.Table("sys_admin sa").
		Select("sa.*, sar.role_id").
		Joins("left join sys_admin_role sar on sar.admin_id = sa.id").
		Joins("left join sys_role sr on sar.role_id = sr.id").
		First(&sysAdminInfo, Id)
	result.Success(c, sysAdminInfo)
}

// CreateSysAdmin 修改用户
// @Summary 修改用户
// @Tags 用户相关接口
// @Produce json
// @Description 修改用户
// @Param data body model.UpdateSysAdminDto true "data"
// @Success 200 {object} result.Result
// @router /api/sysAdmin/update [put]
func UpdateSysAdmin(c *gin.Context) {
	// 绑定参数并校验必填
	var dto model.UpdateSysAdminDto
	_ = c.BindJSON(&dto)
	err := validator.New().Struct(dto)
	if err != nil {
		result.Failed(c, int(result.ApiCode.MisssParameter), result.ApiCode.GetMessage(result.ApiCode.MisssParameter))
		return
	}
	// 先查询再修改
	var sysAdmin model.SysAdmin
	core.Db.First(&sysAdmin, dto.ID)
	sysAdmin.Username = dto.Username
	sysAdmin.Nickname = dto.Nickname
	sysAdmin.Phone = dto.Phone
	sysAdmin.Email = dto.Email
	sysAdmin.Note = dto.Note
	sysAdmin.Status = dto.Status
	sysAdmin.Sex = dto.Sex
	core.Db.Save(&sysAdmin)
	//删除之前的角色再分配新的角色
	var sysAdminRole model.SysAdminRole
	core.Db.Where("admin_id = ?", dto.ID).Delete(&model.SysAdminRole{})
	sysAdminRole.AdminId = dto.ID
	sysAdminRole.RoleId = dto.RoleId
	core.Db.Create(&sysAdminRole)

	result.Success(c, true)
}

// DeleteSysAdmin 根据id删除用户
// @Summary 根据id删除用户
// @Tags 用户相关接口
// @Produce json
// @Description 根据id删除用户
// @Param data body model.SysAdminIdDto true "data"
// @Success 200 {object} result.Result
// @router /api/sysAdmin/delete [delete]
func DeleteSysAdmin(c *gin.Context) {
	// 绑定参数
	var dto model.SysAdminIdDto
	_ = c.BindJSON(&dto)

	core.Db.Delete(&model.SysAdmin{}, dto.ID)
	core.Db.Where("admin_id = ?", dto.ID).Delete(&model.SysAdminRole{})
	result.Success(c, true)
}

// UpdateSysAdminStatus 设置用户状态
// @Summary 设置用户状态
// @Tags 用户相关接口
// @Produce json
// @Description 设置用户状态
// @Param data body model.UpdateSysAdminStatusDto true "data"
// @Success 200 {object} result.Result
// @router /api/sysAdmin/updateStatus [put]
func UpdateSysAdminStatus(c *gin.Context) {
	// 绑定参数
	var dto model.UpdateSysAdminStatusDto
	_ = c.BindJSON(&dto)

	var sysAdmin model.SysAdmin
	core.Db.First(&sysAdmin, dto.ID)
	sysAdmin.Status = dto.Status
	core.Db.Save(&sysAdmin)
	result.Success(c, true)
}

// ResetSysAdminPassword 重置用户密码
// @Summary 重置用户密码
// @Tags 用户相关接口
// @Produce json
// @Description 重置用户密码
// @Param data body model.ResetSysAdminPasswordDto true "data"
// @Success 200 {object} result.Result
// @router /api/sysAdmin/updatePassword [put]
func ResetSysAdminPassword(c *gin.Context) {
	// 绑定参数
	var dto model.ResetSysAdminPasswordDto
	_ = c.BindJSON(&dto)

	var sysAdmin model.SysAdmin
	core.Db.First(&sysAdmin, dto.ID)
	sysAdmin.Password = utils.EncryptionMd5(dto.Password)
	core.Db.Save(&sysAdmin)
	result.Success(c, true)
}

// GetSysAdminList 分页查询用户列表
// @Summary 分页查询用户列表
// @Tags 用户相关接口
// @Produce json
// @Description 分页查询用户列表
// @Param pageNum query int false "分页数"
// @Param pageSize query int false "每页数"
// @Param username query string false "用户名称"
// @Param status query string false "用户状态：1:启用，2:禁用"
// @Param beginTime query string false "开始时间"
// @Param endTime query string false "结束时间"
// @Success 200 {object} result.Result
// @router /api/sysAdmin/list [get]
func GetSysAdminList(c *gin.Context) {
	PageNum, _ := strconv.Atoi(c.Query("pageNum"))
	PageSize, _ := strconv.Atoi(c.Query("pageSize"))
	Username := c.Query("username")
	Status := c.Query("status")
	BeginTime := c.Query("beginTime")
	EndTime := c.Query("endTime")

	if PageNum < 1 {
		PageNum = 1
	}
	if PageSize < 1 {
		PageSize = 10
	}

	var sysAdminVos []model.SysAdminVo
	var total int64
	curDb := core.Db.Table("sys_admin sa").
		Select("sa.*, sr.role_name").
		Joins("left join sys_admin_role sar on sa.id = sar.admin_id").
		Joins("left join sys_role sr on sar.role_id = sr.id")
	if Username != "" {
		curDb = curDb.Where("sa.username = ?", Username)
	}
	if Status != "" {
		curDb = curDb.Where("sa.status = ?", Status)
	}
	if BeginTime != "" && EndTime != "" {
		curDb = curDb.Where("sa.create_time between ? and ?", BeginTime, EndTime)
	}
	curDb.Count(&total).Limit(PageSize).Offset((PageNum - 1) * PageSize).Order("sa.create_time desc").Find(&sysAdminVos)
	result.Success(c, map[string]interface{}{"total": total, "pageSize": PageSize, "pageNum": PageNum, "list": sysAdminVos})
}

// Login 登录
// @Summary 登录
// @Tags 用户相关接口
// @Produce json
// @Description 登录
// @Param data body model.LoginDto true "data"
// @Success 200 {object} result.Result
// @router /api/sysAdmin/login [post]
func Login(c *gin.Context) {
	// 绑定参数并校验必填
	var dto model.LoginDto
	_ = c.BindJSON(&dto)
	err := validator.New().Struct(dto)
	if err != nil {
		result.Failed(c, int(result.ApiCode.MisssParameter), result.ApiCode.GetMessage(result.ApiCode.MisssParameter))
		return
	}
	// 查询用户信息
	sysAdmin := GetSysAdminByName(dto.Username)
	if sysAdmin.Status == constant.DisableStatus {
		result.Failed(c, int(result.ApiCode.StatusDisabled), result.ApiCode.GetMessage(result.ApiCode.StatusDisabled))
		return
	}
	if sysAdmin.ID > 0 {
		// 	校验密码是否正确
		if sysAdmin.Password != utils.EncryptionMd5(dto.Password) {
			result.Failed(c, int(result.ApiCode.PasswordNotTrue), result.ApiCode.GetMessage(result.ApiCode.PasswordNotTrue))
			return
		}
		// 生成token
		token, _ := core.GenerateTokenByAdmin(sysAdmin)
		global.Log.Infof("用户token: %s", token)
		// 组装用户信息 todo
		// 左侧菜单数据 todo
		// 权限累表 todo
		// 返回信息
		result.Success(c, map[string]any{"token": token})
	} else {
		result.Failed(c, int(result.ApiCode.SysAdminIsNotExists), result.ApiCode.GetMessage(result.ApiCode.SysAdminIsNotExists))
	}
}
